package com.googlecode.jsimplemarket.wicket.components.grid;

import com.googlecode.jsimplemarket.model.AbstractEntitate;
import com.googlecode.jsimplemarket.model.IEntitate;
import com.googlecode.jsimplemarket.repository.GenericOrder;
import com.googlecode.jsimplemarket.repository.GenericProperty;
import com.googlecode.jsimplemarket.repository.GenericRestriction;
import com.googlecode.jsimplemarket.service.GenericService;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 *
 * @author alex
 */
@Service(value = "defaultGridAction")
@Scope(value = "prototype")
public class DefaultGridAction<T extends IEntitate> implements GridAction<T> {

    private static final long serialVersionUID = 1L;
    @Resource(name="genericService")
    private GenericService genericService;

    private GenericOrder getGenericOrder(SortParam sort) {
        if (sort == null) {
            return null;
        }
        String property = sort.getProperty().toString();
        GenericProperty genericProperty = GenericProperty.getInstance(property);

        return new GenericOrder(genericProperty, sort.isAscending());
    }

    @Override
    public Iterator<T> getList(Class<T> persistentClass, List<GenericRestriction> genericProperties, List<GenericOrder> genericOrdersParameter, SortParam sort, long firstResult, long maxResults) {
    	
    	List<GenericOrder> genericOrders=genericOrdersParameter;
    	GenericOrder order = getGenericOrder(sort);
        if (order == null) {
            return genericService.getList(persistentClass, firstResult, maxResults, genericProperties, genericOrders).iterator();
        }
        genericOrders = new ArrayList<GenericOrder>();
        genericOrders.add(order);
        return genericService.getList(persistentClass, firstResult, maxResults, genericProperties, genericOrders).iterator();
    }

    @Override
    public long getCount(Class<T> persistentClass, List<GenericRestriction> genericProperties) {
        if (genericProperties == null) {
            return genericService.getCount(persistentClass);
        }
        return genericService.getCount(persistentClass, genericProperties.toArray(new GenericRestriction[genericProperties.size()]));
    }

    @Override
    public T load(Class<T> persistentClass, T model) {
        if (model instanceof AbstractEntitate) {
            AbstractEntitate entitate = (AbstractEntitate) model;
            return (T) genericService.getById(persistentClass, entitate.getId());
        } else {
            return null;
        }
    }
}
